package com.cj.myblog.controller.admin;

import com.cj.myblog.constants.Constants;
import com.cj.myblog.controller.BaseController;
import com.cj.myblog.model.PageBean;
import com.cj.myblog.model.PluginDo;
import com.cj.myblog.model.Result;
import com.cj.myblog.plugin.PluginClassRegister;
import com.cj.myblog.service.PluginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import static com.cj.myblog.constants.Constants.*;

/**
 * Created by jujunchen on 2017/8/29.
 */
@Controller
@RequestMapping("/admin/plugin/")
public class PluginController extends BaseController{

    @Autowired
    private PluginService pluginService;


    @GetMapping(ADD)
    public void add(){
        PluginClassRegister.register();
    }


    @GetMapping(LIST)
    public void list(ModelMap modelMap){
        modelMap.put("devMode", Constants.options.get("devMode"));
    }


    /**
     * 插件保存
     * @param pluginDo
     */
    @ResponseBody
    @PostMapping(SAVE)
    public void save(PluginDo pluginDo){
        pluginService.save(pluginDo);

    }


    /**
     * 插件列表
     * @param pluginDo
     * @return
     */
    @ResponseBody
    @PostMapping(PAGE)
    public PageBean<PluginDo> page(PluginDo pluginDo){
        PageBean<PluginDo> list = pluginService.findAll(pluginDo);
        return list;
    }


    /**
     * 插件预览
     * @param map
     * @param name
     */
    @GetMapping(VIEW)
    public void view(ModelMap map,String name){
        PluginDo pluginDo = pluginService.getUnInstallPlugin(name);
        map.put("bean",pluginDo);
    }


    /**
     * 插件状态变更
     * @param id
     * @param status
     */
    @ResponseBody
    @GetMapping(EDIT)
    public void edit(Long id,int status){
        PluginDo pluginDo = new PluginDo();
        pluginDo.setId(id);
        pluginDo.setStatus(status);
        pluginService.save(pluginDo);
    }


    /**
     * 插件安装
     * @param skuNumber 插件唯一标识
     * @return
     */
    @ResponseBody
    @PostMapping("install")
    public Result install(String skuNumber){
        Result<String> installResult = pluginService.installPlug(skuNumber);
        return installResult;
    }


    /**
     * 插件卸载
     * @param id
     * @param skuNumber
     */
    @ResponseBody
    @GetMapping("uninstall")
    public void uninstall(Long id,String skuNumber){
        pluginService.uninstall(id,skuNumber);
    }


    /**
     * 插件导出
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping("export")
    public Result export(Long id){
        Result<String> result = pluginService.export(id);
        return result;
    }




}
